<template>
  <div class="app-container">
    <el-row :gutter="24" >
         <!--组织名称-->
         <el-col :span="4" :xs="24">
            <div class="head-container">
               <el-input
                  v-model="deptName"
                  placeholder="请输入组织名称"
                  clearable
                  prefix-icon="Search"
                  style="margin-bottom: 20px"
               />
            </div>
            <div class="head-container">
               <el-tree
                  :data="deptOptions"
                  class="custom-tree"
                  :props="{ label: 'deptName', children: 'children' }"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  :default-checked-keys="defaultCheckedKeys"
                  ref="deptTreeRef"
                  node-key="deptId"
                  highlight-current
                  default-expand-all
                  @node-click="handleNodeClick"
               />
            </div>
         </el-col>
         <el-col :span="0.5" :xs="24" style="height: auto;">
            <el-divider direction="vertical" style="height: 100%;margin-left: 0px;margin-right: 10px;"/>
         </el-col>
         <!-- 领导班子 -->
         <el-col :span="19" :xs="24">
          
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane :label="numberToChinese(item.year)" :name="'tab_'+index" v-for="(item, index) in TeamRecordList" :key="index">
              <div class="table-container">
                <el-row>
                  <el-col :span="7"></el-col>
                  <el-col :span="9" style="height: 28px;color: #333;font-size: 20px;text-align: left;font-family: PingFangSC-Medium;">
                      {{item.deptName}}{{numberToChinese(item.year)}}领导班子
                  </el-col>
                  <el-col :span="8" style="display: flex;justify-content: flex-end;">
                    <el-button
                      icon="Delete"
                      @click="handleDelete(item)"
                      v-hasPermi="['partybuilding:TeamRecord:remove']">
                      删除换届
                    </el-button>
                    <el-button
                      icon="Edit"
                      @click="handleUpdate(item)"
                      v-hasPermi="['partybuilding:TeamRecord:edit']">
                      换届信息
                    </el-button>
                    <el-button
                      icon="User"
                      @click="handleMemberAdd(item)"
                      v-hasPermi="['partybuilding:TeamPerson:add']">
                      添加成员
                    </el-button>
                  </el-col>
                </el-row>

                <el-row style="margin-top: 20px;">
                    <div class="cardItem" v-for="(elem, elemIndex) in item.teamPersons" :key="elem">
                        <div class="cardItem-cover">
                          <el-image style="width: 150px;height: 210px;text-align: center;" :src="baseUrl+elem.pictureUrl"></el-image>
                        </div>
                        <div class="cardItem-body">
                          <div style="text-align: center; color: black;font-weight: 500;font-size: 16px!important;"><a>{{ elem.userName }}</a></div>
                          <div style="text-align: center; color: rgba(0, 0, 0, .45);"><a>{{ selectDictLabel(pb_team_duty, elem.duty) }}</a></div>
                        </div>
                        <div class="cardItem-actions">
                          <a style="padding: 0px 10px;" @click="handleMemberUpdate(elem, item.year)" v-hasPermi="['partybuilding:TeamPerson:edit']">修改</a>
                          <el-divider direction="vertical"/>
                          <a style="padding: 0px 10px;" @click="handleMemberDelete(elem)" v-hasPermi="['partybuilding:TeamPerson:remove']">删除</a>
                        </div>
                    </div>
                </el-row>

              </div>
            </el-tab-pane>
          </el-tabs>

          <div style="position: absolute;top: 0px;right: 44px;">
            <el-button
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['partybuilding:TeamRecord:add']">
              新增换届
            </el-button>
          </div>

         </el-col>
    </el-row>

    <!-- 添加或修改班子记录对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="TeamRecordRef" :model="form" :rules="rules" label-width="109px">
        <el-row>
        <!--组织名称-->
        <el-col :span="12">
          <el-form-item label="党组织名称" prop="deptName" style="width: 100%;">
            <el-input v-model="form.deptName" placeholder="请输入党组织名称" disabled/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="届数" prop="year" style="width: 100%;">
            <el-input-number v-model="form.year" :min="1" placeholder="请输入届数" style="width: 100%;"/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="任职年限" prop="yearLimit" style="width: 100%;">
            <el-select v-model="form.yearLimit" placeholder="请选择任职年限">
                <el-option
                    v-for="dict in pb_team_appointment_years"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="换届时间" prop="transTime" style="width: 100%;">
            <el-date-picker clearable
              v-model="form.transTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择换届时间"
              style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="应到人数" prop="shouldCount" style="width: 100%;">
            <el-input-number v-model="form.shouldCount" :min="0" placeholder="请输入应到人数" style="width: 100%;"/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="实到人数" prop="realisticCount" style="width: 100%;">
            <el-input-number v-model="form.realisticCount" :min="0" placeholder="请输入实到人数" style="width: 100%;"/>
          </el-form-item>
        </el-col>


        <el-col :span="12">
          <el-form-item label="换届形式" prop="way" style="width: 100%;">
            <el-select v-model="form.way" placeholder="请选择换届形式">
                <el-option
                    v-for="dict in pb_team_trans_way"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="沿用上届成员" prop="iscontinue" style="width: 100%;">
            <el-select v-model="form.iscontinue" placeholder="是否沿用上届成员">
                <el-option
                    v-for="dict in pb_iscontinue"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择人员弹窗 -->
    <select-people ref="peopleRef" :parentMethod="selectPeopleMethod"></select-people>

    <!-- 添加或修改成员对话框 -->
    <el-dialog :title="memberTitle" v-model="memberOpen" width="900px" append-to-body>
      <el-form ref="MemberRecordRef" :model="memberForm" :rules="memberRules" label-width="109px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="党组织名称" prop="deptName" style="width: 100%;">
              <el-input v-model="memberForm.deptName" placeholder="请输入党组织名称" disabled/>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="届数" prop="year" style="width: 100%;">
              <el-input v-model="memberForm.year" placeholder="请输入届数" disabled/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="姓名" prop="userName" style="width: 100%;">
              <el-input v-model="memberForm.userName" @click="handleClickPeople" placeholder="请选择姓名" style="width: 100%;"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="职务名称" prop="duty" style="width: 100%;">
              <el-select v-model="memberForm.duty" placeholder="请选择职务名称">
                <el-option
                    v-for="dict in pb_team_duty"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="任职方式" prop="appointment" style="width: 100%;">
              <el-select v-model="memberForm.appointment" placeholder="请选择任职方式">
                <el-option
                    v-for="dict in pb_team_appointment"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="任职时间" prop="appointTime" style="width: 100%;">
              <el-date-picker clearable
                v-model="form.appointTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择任职时间"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="任职年限" prop="appointYear" style="width: 100%;">
              <el-select v-model="memberForm.appointYear" placeholder="请选择任职年限">
                  <el-option
                      v-for="dict in pb_team_appointment_years"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="任职文号" prop="appointCode" style="width: 100%;">
              <el-input v-model="memberForm.appointCode" placeholder="请输入任职文号" style="width: 100%;"/>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="行政职务" prop="xzDuty" style="width: 100%;">
              <el-input v-model="memberForm.xzDuty" placeholder="请输入行政职务" style="width: 100%;"/>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="排序" prop="sortNum" style="width: 100%;">
              <el-input-number v-model="memberForm.sortNum" :min="1" placeholder="请输入排序" style="width: 100%;"/>
            </el-form-item>
          </el-col>

          <el-col :span="24">
              <el-form-item label="照片" prop="pictureUrl">
                <image-upload
                    v-model="memberForm.pictureUrl"
                    :multiple="true"
                    :limit="1"
                    :file-type="['jpg', 'png', 'jpeg']">
                </image-upload>
                <div style="position: absolute;left: 1px;top: 188px;font-size: 12px;">建议上传1寸照片 尺寸295*413</div>
              </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitMemberForm">确 定</el-button>
          <el-button @click="cancelMember">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
  </div>
</template>

<script setup name="TeamRecord">
import { queryChilds, listTeamRecord, getTeamRecord, delTeamRecord, addTeamRecord, updateTeamRecord } from "@/api/partybuilding/TeamRecord";
import { getTeamPerson, delTeamPerson, addTeamPerson, updateTeamPerson } from "@/api/partybuilding/TeamPerson";
import SelectPeople from '../MeetingInfo/component/SelectOnePeople.vue'
import { listOrg } from "@/api/partybuilding/Org";
import { ref } from "vue";
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const { proxy } = getCurrentInstance();

const { pb_team_trans_way } = proxy.useDict("pb_team_trans_way");
const { pb_team_appointment_years } = proxy.useDict("pb_team_appointment_years");

const TeamRecordList = ref([]);
const open = ref(false);
const loading = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");
const selectedDeptId = ref("");
const selectedDeptName = ref("");
const deptOptions = ref(undefined);
const deptName = ref("");
const activeName = ref("tab_0");
const memberOpen = ref(false);
const memberTitle = ref("");
const pb_iscontinue = ref([{value:0,label:'否'},{value:1,label:'是'}]);
const defaultCheckedKeys = ref([100]); // 默认勾选的节点id
const peopleRef = ref(null);
const { pb_team_duty } = proxy.useDict("pb_team_duty");
const { pb_team_appointment } = proxy.useDict("pb_team_appointment");

const data = reactive({
  form: {},
  memberForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 99,
    deptId: null,
    deptName: null,
    year: null,
    yearLimit: null,
    transTime: null,
    shouldCount: null,
    realisticCount: null,
    way: null,
    iscontinue: null,
    status: null
  },
  queryPeopleParams: {
    pageNum: 1,
    pageSize: 900,
    deptId: null,
  },
  rules: {
    year: [
      { required: true, message: "届数不能为空", trigger: "blur" }
    ]    
  },
  memberRules: {
    userName: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ]
  },
});

const { queryParams, queryPeopleParams, form, memberForm, rules, memberRules } = toRefs(data);

//树型单击
const handleClick = (tab, event) => {
  console.log("handleClick=" + tab, event)
}

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 根据名称筛选部门树 */
watch(deptName, val => {
  proxy.$refs["deptTreeRef"].filter(val);
});

/** 查询部门下拉树结构 */
function getDeptTree() {
  listOrg().then(response => {
    deptOptions.value = proxy.handleTree(response.rows, "deptId");
    nextTick(() => {
      proxy.$refs["deptTreeRef"].setCurrentKey(deptOptions.value[0].deptId)
      handleNodeClick(deptOptions.value[0])
    })   
  });
};

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.deptId;
  selectedDeptId.value = data.deptId;
  selectedDeptName.value = data.deptName;
  handleQuery();
};

/** 数字转中文大写 */
function numberToChinese(num) {
  if (num === null || num === undefined) {
    return "";
  }
  const digitMap = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
  const unitMap = ["", "十", "百", "千", "万", "亿"];
 
  let chinese = "第";
  let unitIndex = 0;
 
  if (num === 0) {
    chinese += digitMap[0];
  }else{
    while (num > 0) {
      const digit = num % 10;
      if (digit !== 0 || chinese.length === 0 || chinese[0] !== digitMap[0]) {
        chinese += digitMap[digit] + unitMap[unitIndex];
      }
      num = Math.floor(num / 10);
      unitIndex++;
    }
  }
  return chinese+"届";
}

/** 查询班子记录列表 */
function getList() {
  if (queryParams.value.deptId!=null){
    loading.value = true;
    queryChilds(queryParams.value).then(response => {
      TeamRecordList.value = response.data;
      total.value = response.total;
      loading.value = false;
    });
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 班子表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    deptName: null,
    year: null,
    yearLimit: null,
    transTime: null,
    shouldCount: null,
    realisticCount: null,
    way: null,
    iscontinue: null,
    status: null
  };
  proxy.resetForm("TeamRecordRef");
}

// 班子表单重置
function memberReset() {
  memberForm.value = {
    id: null,
    deptId: null,
    deptName: null,
    year: null,
    userId: null,
    userName: null,
    duty: null,
    appointment: null,
    appointTime: null,
    appointYear: null,
    appointCode: null,
    xzDuty: null,
    sortNum: null,
    pictureUrl: null,
    teamId: null
  };
  proxy.resetForm("MemberRecordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

//单击人员
function handleClickPeople() {
  peopleRef.value.show();
}

//人员回调函数
function selectPeopleMethod(uIdList, uNameList) {
  memberForm.value.userId = uIdList;
  memberForm.value.userName = uNameList;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增换届";
  form.value.iscontinue = 1;
  form.value.deptId = selectedDeptId.value;
  form.value.deptName = selectedDeptName.value;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getTeamRecord(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "更新换届";
  });
}

/** 成员新增按钮操作 */
function handleMemberAdd(row) {
  memberReset();
  memberOpen.value = true;
  memberForm.value.teamId = row.id;
  //复制党组织信息
  memberForm.value.deptId = selectedDeptId.value;
  memberForm.value.deptName = selectedDeptName.value;
  memberForm.value.year = row.year;
  memberTitle.value = "添加成员";
}

/** 成员修改按钮操作 */
function handleMemberUpdate(row, year) {
  memberReset();
  const _id = row.id
  getTeamPerson(_id).then(response => {
    memberForm.value = response.data;
    memberForm.value.duty = memberForm.value.duty!=null? memberForm.value.duty+'':null;
    memberForm.value.appointment = memberForm.value.appointment!=null? memberForm.value.appointment+'':null;
    memberForm.value.appointYear = memberForm.value.appointYear!=null? memberForm.value.appointYear+'':null;
    memberForm.value.year = year;
    memberOpen.value = true;
    memberTitle.value = "更新成员";
  });
}

/** 成员删除按钮操作 */
function handleMemberDelete(row) {
  const _ids = row.id;
  proxy.$modal.confirm('您确定要删除成员信息吗？').then(function() {
    return delTeamPerson(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["TeamRecordRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateTeamRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTeamRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 取消成员按钮
function cancelMember() {
  memberOpen.value = false;
  memberReset();
}

/** 成员提交按钮 */
function submitMemberForm() {
  proxy.$refs["MemberRecordRef"].validate(valid => {
    if (valid) {
      if (memberForm.value.id != null) {
        updateTeamPerson(memberForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成员成功!");
          memberOpen.value = false;
          getList();
        });
      } else {
        console.log(memberForm.value)
        addTeamPerson(memberForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成员成功!");
          memberOpen.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('您确定要删除本届班子吗？').then(function() {
    return delTeamRecord(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('partybuilding/TeamRecord/export', {
    ...queryParams.value
  }, `TeamRecord_${new Date().getTime()}.xlsx`)
}

getDeptTree();
getList();
</script>
<style>
  .custom-tree .el-tree-node__label {
    display: inline-block; /* 允许宽度根据内容调整 */
    max-width: 250px; /* 设置最大宽度，根据需要调整 */
    overflow: hidden; /* 超出部分隐藏 */
    text-overflow: ellipsis; /* 文本溢出显示省略号 */
    white-space: nowrap; /* 不换行 */
    vertical-align: middle; /* 垂直居中 */
  }
</style>
<style lang='scss' scoped>
.cardItem {
  margin-right: 55px;
  display: inline-block;
  font-size: 14px!important;
  .cardItem-cover{
    cursor: pointer;
  }
  .cardItem-body{
    overflow: hidden;
  }
  .cardItem-actions{
    display: none;
    margin-top: 9px;
    background: #fafafa;
    border-top: 1px solid #e8e8e8;
    width: 150px;
    text-align: center;
    padding: 10px;
    float: left;
  }
  .cardItem-actions a:hover {
    color: #ff4d4f;
  }
}
.cardItem:hover .cardItem-actions{
  display: block;
}
</style>